package com.ultrapower.util.topology;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import com.ultrapower.bean.ApplicationBean;

public class AgentHistogram {
	  /**
     * to uniquely identify a host from UI, we can use things like hostname, agentId, endpoint, etc
     */
    private final ApplicationBean agentId;

    private final Map<Long, TimeHistogram> timeHistogramMap;

    public AgentHistogram(ApplicationBean agentId) {
        if (agentId == null) {
            throw new NullPointerException("agentId must not be null");
        }

        this.agentId = agentId;
        this.timeHistogramMap = new HashMap<>();
    }

    public AgentHistogram(AgentHistogram copyAgentHistogram) {
        if (copyAgentHistogram == null) {
            throw new NullPointerException("copyAgentHistogram must not be null");
        }

        this.agentId = copyAgentHistogram.agentId;

        this.timeHistogramMap = new HashMap<>();
        addTimeHistogram(copyAgentHistogram.timeHistogramMap.values());
    }

    public String getId() {
        return agentId.getName();
    }

    public ApplicationBean getAgentId() {
        return agentId;
    }

    public short getServiceType() {
        return agentId.getServiceTypeCode();
    }

    public Histogram getHistogram() {
        Histogram histogram = new Histogram(agentId.getServiceTypeCode());
        for (TimeHistogram timeHistogram : timeHistogramMap.values()) {
            histogram.add(timeHistogram);
        }
        return histogram;
    }

    public Collection<TimeHistogram> getTimeHistogram() {
        return timeHistogramMap.values();
    }

    public void addTimeHistogram(TimeHistogram timeHistogram) {
        TimeHistogram find = this.timeHistogramMap.get(timeHistogram.getTimeStamp());
        if (find == null) {
            find = new TimeHistogram(agentId.getServiceTypeCode(), timeHistogram.getTimeStamp());
            this.timeHistogramMap.put(timeHistogram.getTimeStamp(), find);
        }
        find.add(timeHistogram);
    }

    public void addTimeHistogram(Collection<TimeHistogram> histogramList) {
        if (histogramList == null) {
            throw new NullPointerException("histogramList must not be null");
        }
        for (TimeHistogram timeHistogram : histogramList) {
            addTimeHistogram(timeHistogram);
        }
    }



    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("AgentHistogram{");
        sb.append("agent='").append(agentId.getName()).append('\'');
        sb.append(", serviceType=").append(agentId.getServiceTypeCode());
        sb.append(", ").append(timeHistogramMap);
        sb.append('}');
        return sb.toString();
    }

}
